package com.lse_api.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lse_api.utils.ReturnMsg;
import com.lse_api.utils.Status;
import com.lse_api.utils.pdfutil.stringutil.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring security token鉴权过滤器
 *
 * @author 祁雪
 */
@Slf4j
@Component
public class AuthTokenConfig implements HandlerInterceptor, ReturnMsg {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 此处username为LSE token
        String username = request.getHeader("user_key");

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        if (!StringUtils.isEmpty(username)) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            // 鉴别到用户信息才可下一步
            if (userDetails != null && userDetails.isEnabled()) {
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails,
                                null, userDetails.getAuthorities());
                // 把当前登陆用户放到上下文中
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                        request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                return true;
            } else {
                // 用户不合法，清除上下文
                SecurityContextHolder.clearContext();
                response.getWriter().print(new ObjectMapper().writeValueAsString(Status.error(TOKEN_READ_IS_NULL)));
            }
        } else {
            response.getWriter().print(new ObjectMapper().writeValueAsString(Status.error(TOKEN_IS_NULL)));
        }

        return false;
    }
}
